<?php


namespace App\library\services;


use App\library\common\Curl;
use App\Models\SecondHandHouse;
use App\Models\UserConsume;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class SecondHouseService extends BaseServices
{
    /**
     * Author:YangXinPeng
     * 根据租卖方式获取二手房列表
     * @param $type
     * @param $province
     * @return array
     */
    public static function getDataBySale($type, $province)
    {
        if (!isset($type) || !isset($province)) {
            return self::fail('参数错误');
        }
        if (!is_numeric($type) || !is_numeric($province)) {
            return self::fail('参数类型错误');
        }
        $data = SecondHandHouse::with(['agent', 'houseType', 'fitUp'])
            ->where('sale_type', $type)
            ->where('province', $province)
            ->get();
        $data && $data = $data->toArray();
        $res = [];
        foreach ($data as $value) {
            $days = $value['days'];
            $times = $days * 24 * 60 * 60;
            $createTime = $value['created_at'];
            $validity = intval($times) + intval($createTime);
            if ($validity > time()) {
                $res[] = $value;
            }
        }
        return self::success('成功', $res);
    }

    /**
     * Author:YangXinPeng
     * 根据主键ID获取二手房信息
     * @param $id
     * @return array
     */
    public static function getDataById($id)
    {
        if (!is_numeric($id)) {
            return self::fail('参数类型错误');
        }
        $data = SecondHandHouse::with(['agent', 'houseType', 'fitUp', 'forward'])
            ->where('id', $id)
            ->first();
        $data && $data = $data->toArray();
        $config = $data['config'];
        $arr = explode('"', $config);
        $configIds = [];
        foreach ($arr as $value) {
            if (is_numeric($value)) {
                array_push($configIds, $value);
            }
        }
        $res = FangAttrsService::getAttrName($configIds);
        unset($data['config']);
        $data['config'] = $res;
        return self::success('成功', $data);
    }

    /**
     * Author:Zhongyuan Lu
     * 房源添加
     * @param $userRelease
     * @return array
     */
    public static function createHouse($userRelease)
    {
        DB::beginTransaction();
        Redis::select(config('setting.redis_map'));
        try {
            $id = SecondHandHouse::create($userRelease)->id;
            $address = $userRelease['address'];
            $url = sprintf(config('setting.location'), $address);
            //获取经纬度
            $data = Curl::geturl($url);
            $where = [];
            $latitude = $data['result']['location']['lat'];
            $longitude = $data['result']['location']['lng'];
            $where['latitude'] = $latitude;
            $where['longitude'] =$longitude;
            $flag = SecondHandHouse::where('id', $id)->update($where);
            if ($flag) {
                DB::commit();
                $key = config('setting.map').$userRelease['province'];
                Redis::geoadd($key,$longitude,$latitude,$id);
                return self::success('房源添加成功', $id);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return self::fail('房源添加失败');
        }
    }

    /**
     * Author:YangXinPeng
     * 定期二手房源同步redis
     * @return array
     */
    public static function dbToRedis()
    {
        Redis::select(config('setting.redis_map'));
        $data = SecondHandHouse::all();
        $data && $data = $data->toArray();
        foreach ($data as $value){
            $latitude = $value['latitude'];
            $longitude = $value['longitude'];
            $province = $value['province'];
            $key = config('setting.map').$province;
            Redis::geoadd($key,$longitude,$latitude,$value['id']);
        }
        Log::info('同步完成');
    }

    /**
     * Author:YangXinPeng
     * GEO查询范围内二手房源信息
     * @param $province
     * @param $latitude
     * @param $longitude
     * @param $number
     * @return array
     */
    public static function findByRedis($province,$latitude,$longitude,$number)
    {
        Redis::select(config('setting.redis_map'));
        $key = config('setting.map').$province;
        $data = Redis::GEORADIUS($key,$longitude,$latitude,$number,'km');
        $arr = [];
        foreach ($data as $value){
            $info = SecondHandHouse::find($value);
            $info && $info=$info->toArray();
            $arr[] = $info;
        }
        return self::success('成功',$arr);
    }

    /**
     * Author:YangXinPeng
     * 根据经纬度条件查询二手房源
     * @param $latitude
     * @param $longitude
     * @return array
     */
    public static function findByItude($latitude,$longitude)
    {
       $data = SecondHandHouse::all();
       $data && $data = $data->toArray();
       $latitude =  substr(floatval($latitude),0,strpos($latitude,".")+2);
       $longitude = substr(floatval($longitude),0,strpos($longitude,".")+2);
       $arr = [];
       foreach ($data as $value){
         $nowLat = substr(floatval($value['latitude']),0,strpos($value['latitude'],".")+2);
         $nowLon = substr(floatval($value['longitude']),0,strpos($value['longitude'],".")+2);
         if ($latitude == $nowLat && $longitude == $nowLon){
             $arr[] = $value;
         }
       }
       return self::success('成功',$arr);
    }

    /**
     * Author:YangXinPeng
     * 查询经纪人旗下房源
     * @param $aid
     * @return array
     */
    public static function  findByAid($aid)
    {
        $data = SecondHandHouse::where('agent_id',$aid)
            ->where('sale_type',2)
            ->get();
        $data && $data = $data->toArray();
        $res = [];
        foreach ($data as $value) {
            $days = $value['days'];
            $times = $days * 24 * 60 * 60;
            $createTime = $value['created_at'];
            $validity = intval($times) + intval($createTime);
            if ($validity > time()) {
                $res[] = $value;
            }
        }
        return self::success('成功', $res);
    }

    public static function findFang($where,$aid)
    {
        $model = DB::table('second_hand_house')->where('agent_id',$aid);
        if (empty($where['floor'])){
            unset($where['floor']);
        }else{
            $model = $model->whereIn('floor',$where['floor']);
            unset($where['floor']);
        }
        if (empty($where['minArea']) || empty($where['maxArea'])){
            unset($where['minArea']);
            unset($where['maxArea']);
        }else{
            $model = $model->whereBetween('votes', [1, 100]);
            unset($where['minArea']);
            unset($where['maxArea']);
        }
        if (empty($where['price'])){
            unset($where['price']);
        }else{
            if ($where['price'][0] == '<>'){
                $model = $model->whereBetween('votes', [$where['price'][1], $where['price'][2]]);
            }else{
                $model = $model->where('price',$where['price'][0],$where['price'][1]);
            }
            unset($where['price']);
        }
        if (empty($where['forward'])){
            unset($where['forward']);
        }
        if (empty($where['fit_up'])){
            unset($where['fit_up']);
        }
        if (empty($where['region'])){
            unset($where['region']);
        }
        if ($where['house_type'] == 0){
            unset($where['house_type']);
        }
        $data = $model->where($where)->get();
        $data && $data = json_decode(json_encode($data),true);
        $res = [];
        foreach ($data as $value) {
            $days = $value['days'];
            $times = $days * 24 * 60 * 60;
            $createTime = $value['created_at'];
            $validity = intval($times) + intval($createTime);
            if ($validity > time()) {
                $res[] = $value;
            }
        }
        return self::success('成功', $res);
    }


}
